package com.yang.job.admin.infra.job;

import com.yang.job.admin.domain.gateway.repository.IJobModelRepository;
import com.yang.job.admin.domain.model.YangJobModel;
import com.yang.job.admin.infra.utils.SpringContextUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.List;

public class YangJobContext implements ApplicationListener<ApplicationContextEvent> {
    private static YangJobContext instance;

    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(ApplicationContextEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            System.out.println("刷新了=========");
            YangJobContext.instance = this;
            instance.applicationContext = applicationContext;
            init();
        } else if (event instanceof ContextClosedEvent) {
            System.out.println("销毁了=========");
            shutdown();
        }
    }

    private void init() {
        IJobModelRepository jobModelRepository = SpringContextUtils.getBeanOfType(IJobModelRepository.class);
        List<YangJobModel> yangJobModelList = jobModelRepository.getOpenYangJobModelList();
        for (YangJobModel yangJobModel : yangJobModelList) {
            yangJobModel.submitJob();
        }
    }

    private void shutdown() {
        YangJobManager yangJobManager = SpringContextUtils.getBeanOfType(YangJobManager.class);
        if (yangJobManager == null) {
            return;
        }
        yangJobManager.shutdown();
    }
}
